import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Line
from pyecharts.globals import ThemeType

df = pd.read_excel('全国人口年度数据.xlsx', index_col=0)
df = df.sort_index(axis='columns')
line = Line(init_opts=opts.InitOpts(width='1200px', height='600px', theme=ThemeType.SHINE, page_title='折线图'))
line.add_xaxis(xaxis_data=df.columns.tolist())
line.add_yaxis(series_name='年末总人口', y_axis=df.loc['年末总人口（万人）'])
line.add_yaxis(series_name='城镇人口', y_axis=df.loc['城镇人口（万人）'])
line.add_yaxis(series_name='乡村人口', y_axis=df.loc['乡村人口（万人）'])
line.set_global_opts(
    title_opts=opts.TitleOpts(
        title='2003—2022 年全国年末总人口、城镇人口和乡村人口折线图',
        pos_left='center'),
    yaxis_opts=opts.AxisOpts(name='人口（万人）', name_location='center', name_gap=55, min_=45000),
    legend_opts=opts.LegendOpts(
        pos_right='10%',
        pos_top='5%')
)

line.render('例 7-1.html')